import { createRouter, createWebHistory } from 'vue-router'
import { defineAsyncComponent } from 'vue'
import BrandStory from '../views/BrandStory.vue'
import RecentViews from '../views/RecentViews.vue'
import axios from 'axios'
import { useProductStore } from '../stores/product'
import NProgress from 'nprogress'
import AIChat from '../components/AIChat.vue'
import Cart from '../views/Cart.vue'

// 配置 NProgress
NProgress.configure({ 
  showSpinner: false,
  easing: 'ease',
  speed: 500
})

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: true },
    beforeEnter: async (to) => {
      const productStore = useProductStore()
      try {
        // 并行请求数据
        const [hotProducts, newProducts] = await Promise.all([
          axios.get('/api/products/hot'),
          axios.get('/api/products/new')
        ])
        
        productStore.setPreloadedProducts({
          hot: hotProducts.data,
          new: newProducts.data
        })
      } catch (error) {
        console.error('Failed to preload products:', error)
      }
    }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: () => import('../views/ForgotPassword.vue')
  },
  {
    path: '/reset-password/:token',
    name: 'ResetPassword',
    component: () => import('../views/ResetPassword.vue')
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('../views/ProductDetail.vue'),
    props: true
  },
  {
    path: '/wishlist',
    name: 'Wishlist',
    component: () => import('../views/Wishlist.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('../views/Orders.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/new',
    name: 'NewProducts',
    component: () => import('../views/NewProducts.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/brand-story',
    name: 'BrandStory',
    component: BrandStory,
    meta: {
      title: '品牌故事'
    }
  },
  {
    path: '/hot',
    name: 'HotProducts',
    component: () => import('../views/HotProducts.vue')
  },
  {
    path: '/recent-views',
    name: 'RecentViews',
    component: RecentViews,
    meta: { requiresAuth: true }
  },
  {
    path: '/address',
    name: 'Address',
    component: () => import('../views/Address.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/account/orders',
    name: 'AccountOrders',
    component: () => import('../views/AccountOrders.vue'),
    meta: { requiresAuth: true },
    beforeEnter: async (to, from, next) => {
      const token = localStorage.getItem('token')
      if (!token) {
        next('/login')
        return
      }
      
      try {
        const { data } = await axios.get('/api/orders', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
        to.params.preloadedOrders = data
      } catch (error) {
        console.error('Failed to preload orders:', error)
      }
      next()
    }
  },
  {
    path: '/ai-chat',
    name: 'AIChat',
    component: AIChat,
    meta: { 
      requiresAuth: true,
      title: 'AI客服'
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart,
    meta: { requiresAuth: true }
  },
  {
    path: '/payment/result',
    name: 'PaymentResult',
    component: () => import('../views/PaymentResult.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else {
    NProgress.start()
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router 